<template>
  <view class="address-edit-container">
    <form @submit="submitForm">
      <!-- 收货人 -->
      <view class="form-item">
        <text class="label">收货人</text>
        <input
          class="input"
          name="name"
          v-model="form.name"
          placeholder="请输入收货人姓名"
          placeholder-class="placeholder"
        />
      </view>

      <!-- 手机号码 -->
      <view class="form-item">
        <text class="label">手机号码</text>
        <input
          class="input"
          name="phone"
          v-model="form.phone"
          placeholder="请输入手机号码"
          placeholder-class="placeholder"
          type="number"
        />
      </view>

      <!-- 所在地区 -->
      <view class="form-item" @click="openRegionPicker">
        <text class="label">所在地区</text>
        <input
          class="input"
          disabled
          :value="regionText"
          placeholder="请选择省市区"
          placeholder-class="placeholder"
        />
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>

      <!-- 详细地址 -->
      <view class="form-item">
        <text class="label">详细地址</text>
        <textarea
          class="textarea"
          name="detail"
          v-model="form.detail"
          placeholder="请输入详细地址"
          placeholder-class="placeholder"
        />
      </view>

      <!-- 设为默认 -->
      <view class="form-item default-item">
        <text class="label">设为默认地址</text>
        <switch
          color="$primary-color"
          :checked="form.isDefault"
          @change="form.isDefault = $event.detail.value"
        />
      </view>

      <!-- 省市区选择器 -->
      <region-picker
        ref="regionPicker"
        v-if="showRegionPicker"
        :modelValue="showRegionPicker"
        @confirm="handleRegionConfirm"
      />

      <!-- 提交按钮 -->
      <button class="submit-btn" form-type="submit" :disabled="submitting">
        {{ submitting ? "提交中..." : "保存地址" }}
      </button>

      <!-- 删除按钮（编辑模式下显示） -->
      <button
        class="delete-btn"
        v-if="isEditMode"
        @click="confirmDelete"
        :disabled="submitting"
      >
        删除地址
      </button>
    </form>
  </view>
</template>

<script setup>
import { ref, computed, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { addAddress, updateAddress, deleteAddress } from "@/api/address";
import RegionPicker from "./components/RegionPicker.vue";

const form = ref({
  name: "",
  phone: "",
  province: "",
  city: "",
  district: "",
  detail: "",
  isDefault: false,
});

const showRegionPicker = ref(false);
const submitting = ref(false);
const isEditMode = ref(false);
const addressId = ref(null);

// 计算地区显示文本
const regionText = computed(() => {
  const { province, city, district } = form.value;
  return `${province} ${city} ${district}`;
});
const regionPicker = ref(null);
// 打开省市区选择器
const openRegionPicker = () => {
  console.log("点击了省市区选择"); // 调试日志
  showRegionPicker.value = true;

  // 确保组件已加载
  nextTick(() => {
    if (regionPicker.value) {
      regionPicker.value.open();
    }
  });
};
// 地区选择确认
const handleRegionConfirm = (region) => {
  console.log(region);
  form.value.province = region[0]?.name || "";
  form.value.city = region[1]?.name || "";
  form.value.district = region[2]?.name || "";
};

// 提交表单
const submitForm = async () => {
  if (!validateForm()) return;

  try {
    submitting.value = true;
    if (isEditMode.value) {
      await updateAddress(addressId.value, form.value);
      uni.showToast({ title: "更新成功", icon: "success" });
    } else {
      await addAddress(form.value);
      uni.showToast({ title: "添加成功", icon: "success" });
    }
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (e) {
    uni.showToast({ title: "提交失败", icon: "none" });
  } finally {
    submitting.value = false;
  }
};

// 表单验证
const validateForm = () => {
  const { name, phone, province, city, district, detail } = form.value;

  if (!name) {
    uni.showToast({ title: "请输入收货人姓名", icon: "none" });
    return false;
  }

  if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
    uni.showToast({ title: "请输入正确的手机号码", icon: "none" });
    return false;
  }

  if (!province || !city || !district) {
    uni.showToast({ title: "请选择所在地区", icon: "none" });
    return false;
  }

  if (!detail) {
    uni.showToast({ title: "请输入详细地址", icon: "none" });
    return false;
  }

  return true;
};

// 确认删除
const confirmDelete = () => {
  uni.showModal({
    title: "提示",
    content: "确定要删除该地址吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteAddress(addressId.value);
          uni.showToast({ title: "删除成功", icon: "success" });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } catch (e) {
          uni.showToast({ title: "删除失败", icon: "none" });
        }
      }
    },
  });
};

// 初始化
onLoad((options) => {
  if (options.id) {
    isEditMode.value = true;
    uni.setNavigationBarTitle({ title: "编辑地址" });
    // 实际项目中这里应该调用API获取地址详情
    // 模拟数据
    form.value = {
      name: "张三",
      phone: "13800138000",
      province: "广东省",
      city: "深圳市",
      district: "南山区",
      detail: "科技园路1号",
      isDefault: true,
    };
    addressId.value = options.id;
  }
});
</script>

<style lang="scss" scoped>
.address-edit-container {
  padding: 30rpx;

  .form-item {
    display: flex;
    align-items: center;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    .label {
      width: 180rpx;
      font-size: $font-size-28rpx;
    }

    .input {
      flex: 1;
      font-size: $font-size-28rpx;
      padding-right: 10rpx;
    }

    .textarea {
      flex: 1;
      height: 120rpx;
      font-size: $font-size-28rpx;
      padding-right: 10rpx;
    }

    .placeholder {
      color: #ccc;
    }

    &.default-item {
      justify-content: space-between;
      border-bottom: none;
      margin-top: 20rpx;
    }
  }

  .submit-btn {
    margin-top: 60rpx;
    height: 80rpx;
    line-height: 80rpx;
    background-color: $primary-color;
    color: $text-color-inverse;
    font-size: $font-size-30rpx;
    border-radius: 40rpx;

    &[disabled] {
      background-color: #ffd89e;
    }

    &::after {
      border: none;
    }
  }

  .delete-btn {
    margin-top: 30rpx;
    height: 80rpx;
    line-height: 80rpx;
    background-color: $white-bg;;
    color: #ff4d4f;
    font-size: $font-size-30rpx;
    border-radius: 40rpx;
    border: 1rpx solid #ff4d4f;

    &[disabled] {
      opacity: 0.6;
    }

    &::after {  
      border: none;
    }
  }
}
</style>
